package ru.ifmo.croak.impl.ui.post.team1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ifmo.croak.api.Message;
import ru.ifmo.croak.api.PostService;
import ru.ifmo.croak.util.CroakFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.UUID;

public class PostUI implements Runnable {

    private final PostService postService;

    class PostFrame extends JFrame {
        JTextField author;
        JTextField text;
        JButton submit;

        public PostFrame() {
            super("Enter you post!");
            setLayout(new GridLayout(3, 1));
            author = new JTextField();
            add(author);
            text = new JTextField();
            add(text);
            submit = new JButton("Croak!");
            submit.addActionListener(new QuerySubmitListener());
            add(submit);
            setSize(300, 200);
            setVisible(true);
        }

        private class QuerySubmitListener implements ActionListener {
            public void actionPerformed(ActionEvent actionEvent) {
                Message message = new Message();
                message.setId(UUID.randomUUID());
                message.setTime(System.currentTimeMillis());
                message.setAuthor(author.getText());
                message.setText(text.getText());
                postService.postMessage(message);
            }
        }
    }

    public PostUI(String name) {
        String postProviderName = CroakFactory.getInstance().getProperty(name + ".provider");
        postService = CroakFactory.getInstance().getImplementation(PostService.class, postProviderName);
    }


    public void run() {
        new PostFrame();
    }
}